<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>上传文件demo</title>
  <link rel="stylesheet" href="./index.css">
  <!-- 传文件好用版本2020-12-4 -->
</head>

<body style="min-width: 750px;">
  <input id="file" type="file" multiple class="d-none">
  <button onclick="myUpload()" class="ant-btn ant-btn-primary">上传文件</button>
  <button onclick="getFiles()" class="ant-btn ant-btn-primary">获取服务器文件列表</button>
  <!-- 上传进度条 -->
  <div class="progress">
    <span></span>
  </div>
  <!-- 上传进度条 -->
  <!-- <div id="myFiles">

  </div> -->
  <!-- 测试表格 -->
  <div style="width: 100%;"  class="ant-table table-scall">
    <div class="table-head">
      <table>
        <colgroup>
          <col style="width: 120px;" />
          <col />
          <col style="width: 220px;" />
          <col />
        </colgroup>
        <thead class="ant-table-thead">
          <tr>
            <th>序号</th>
            <th>文件名</th>
            <th>其他信息</th>
          </tr>
        </thead>
      </table>
    </div>
    <div class="table-body">
      <table>
        <colgroup>
          <col style="width: 120px;" />
          <col />
        </colgroup>
        <col style="width: 220px;" />
        <col />
        <tbody class="ant-table-tbody" id="myTbody">


        </tbody>
      </table>
    </div>
  </div>
  <!-- 测试表格 -->
  <iframe src="./websocket.html" width="100%" height="400px" frameborder="no" border="0" marginwidth="0"
    marginheight="0" scrolling="no" allowtransparency="yes"></iframe>
  <script type="text/javascript">
    function myUpload() {
      document.getElementById('file').click()
    }
    var http = function (option) {
      // 过滤请求成功后的响应对象
      function getBody(xhr) {
        var text = xhr.responseText || xhr.response
        if (!text) {
          return text
        }

        try {
          return JSON.parse(text)
        } catch (err) {
          return text
        }
      }

      var xhr = new XMLHttpRequest();
      // 自定义 beforeSend 函数
      if (option.beforeSend instanceof Function) {
        if (option.beforeSend(xhr) === false) {
          return false
        }
      }

      xhr.onreadystatechange = function () {
        if (xhr.status === 200) {
          if (xhr.readyState === 4) {
            // 成功回调
            option.onSuccess(getBody(xhr))
          }
        }
      }

      // 请求失败
      xhr.onerror = function (err) {
        option.onError(err)
      }

      xhr.open(option.type, option.url, true)

      // 当请求为上传文件时回调上传进度
      if (xhr.upload) {
        xhr.upload.onprogress = function (event) {
          if (event.total > 0) {
            event.percent = event.loaded / event.total * 100;
          }
          // 监控上传进度回调
          if (option.onProgress instanceof Function) {
            option.onProgress(event)
          }
        }
      }

      // 自定义头部
      const headers = option.headers || {}
      for (var item in headers) {
        xhr.setRequestHeader(item, headers[item])
      }

      xhr.send(option.data)
    }

    // 测试接口
    http({
      type: 'POST',
      url: 'http://10.100.100.100:3001/test',
      data: JSON.stringify({
        name: 'yolo'
      }),
      onSuccess: function (data) {
        console.log(data)
      },
      onError: function (err) {
        console.log(err)
      }
    })
    document.getElementById('file').onchange = function () {
      var fileList = this.files, formData = new FormData();
      Array.prototype.forEach.call(fileList, function (file) {
        formData.append(file.name, file)
      })
      // 当上传的数据为 file 类型时，请求的格式类型自动会变为 multipart/form-data, 如果头部格式有特定需求，在我的 http 函数中传入 headers<Object> 即可，大家可自己查看，我这里没有什么特殊处理所以就不传了
      http({
        type: 'POST',
        url: 'http://10.100.100.100:3001/upload',
        data: formData,
        onProgress: function (event) {
          console.log(event.percent)
          document.querySelector('.progress span').style.width = event.percent + '%';
        },
        onSuccess: function (data) {
          console.log('上传成功')
        },
        onError: function (err) {
          alert(err)
        }
      })
    }

    function getFiles() {
      http({
        type: 'get',
        url: 'http://10.100.100.100:3001/getFile',
        data: JSON.stringify({
          name: 'yolo'
        }),
        onSuccess: function (data) {
          if (Array.isArray(data.data)) {
            let str = ''
            let str1 = ''
            data.data.forEach((_, i) => {
              str += `<div  class="myFile" onclick="exportTemplate('http://10.100.100.100:3002/getData?fileType=2&fileName=${_}')">${_}</div>`
              str1 += `
              <tr onclick="exportTemplate('http://10.100.100.100:3002/getData?fileType=2&fileName=${_}')">
            <td>${i + 1}</td>
            <td>${_}</td>
            <td>待添加</td>
          </tr>
              `
            })
            // document.getElementById('myFiles').innerHTML = str
            document.getElementById('myTbody').innerHTML = str1
          }
        },
        onError: function (err) {
          console.log(err)
        }
      })
    }
    function exportTemplate(url) {
      const elemIF = document.createElement('iframe');
      elemIF.src = url;
      elemIF.style.display = 'none';
      document.body.appendChild(elemIF);
    }
  </script>
</body>

</html>
